<template>
  <div class="app-container">
    <!--工具栏-->
    <!-- <div class="head-container">
      <search v-if="crud.props.searchToggle" :crud="crud">
        <el-form-item label="关键字">
          <el-input v-model="query.name" placeholder="输入名称或者描述搜索" />
        </el-form-item>
      </search>
      <crudOperation :permission="permission" :opt-show="optShow" />
    </div> -->
    <div class="head-container">
      <Search :crud="crud">
        <el-form-item label="关键字">
            <el-input v-model="query.name" placeholder="输入名称或者描述搜索"></el-input>
        </el-form-item>
      </Search>
      <crudOperation :permission="permission" :opt-show="optShow" />
    </div>
    
    <!-- 表单渲染 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="520px"
    >
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" style="width: 380px;" />
        </el-form-item>
        <el-form-item label="角色类型" prop="type">
          <el-select
            v-model="form.type"
            clearable
            placeholder="请选择角色类型"
            class="filter-item"
            style="width: 380px"
          >
            <el-option
              v-for="item in ROLE"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述信息" prop="remark">
          <el-input v-model="form.remark" style="width: 380px;" rows="5" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table
            ref="table"
            v-loading="crud.loading"
            border
            style="width: 100%;"
            :data="crud.data"
            @selection-change="crud.selectionChangeHandler"
          >
            <!-- <el-table-column :selectable="checkboxT" type="selection" width="55" /> -->
            <el-table-column prop="name" align="center" label="名称" />
            <el-table-column
              prop="type"
              align="center"
              label="角色类型"
            >
              <template slot-scope="scope">
                <span>{{ dict.label.ROLE[scope.row.type] }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              :show-overflow-tooltip="true"
              align="center"
              label="描述"
            />
            <el-table-column
              width="200px"
              prop="createdAt"
              align="center"
              label="创建日期"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createdAt) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-permission="['role:set','role:edit','role:del']" label="操作" align="center" fixed="right">
              <template slot-scope="scope">
                <udOperation :data="scope.row" :permission="permission">
                  <!-- <template slot="left">
                    <el-button v-permission="['role:set']" size="mini" type="text" @click="handleCurrentChange(scope.row)">权限配置</el-button>
                  </template> -->
                </udOperation>
                <el-button size="mini" type="text" @click="handleCurrentChange(scope.row)">权限配置</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </el-card>
      </el-col>
      <!-- 菜单授权 -->
      <el-col v-show="showRoleTree" :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配权限" placement="top">
              <span class="role-span">权限分配：{{ roleName }}</span>
            </el-tooltip>
            <el-button
              v-permission="['role:save']"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >
              保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            accordion
            show-checkbox
            node-key="id"
            :default-expand-all="false"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import crudRoles from '@/api/system/role'
import {
  getDepts
} from '@/api/system/dept'
import CRUD, {
  presenter,
  header,
  form,
  crud
} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getTreeMap } from '@/utils'
import Search from '@/components/Search'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '角色',
  url: 'roles',
  sort: 'level,asc',
  crudMethod: {
    ...crudRoles
  }
})
const defaultForm = {
  id: null,
  name: null,
  type: '',
  remark: null
}
export default {
  name: 'Role',
  components: {
    Treeselect,
    pagination,
    crudOperation,
    rrOperation,
    Search,
    udOperation
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['ROLE'],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      dateScopes: ['全部', '本级', '自定义'],
      level: 3,
      currentId: 0,
      menuLoading: false,
      showButton: false,
      menus: [],
      menuIds: [],
      depts: [],
      permission: {
        add: ['role:add'],
        edit: ['role:edit'],
        del: ['role:del'],
        download: [''],
        downloadSelect: ['']
      },
      optShow: {
        add: true,
        edit: false,
        del: false,
        download: false,
        downloadSelect: false
      },
      rules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        type: [{
          required: true,
          message: '请选择角色类型',
          trigger: 'change'
        }]
      },
      showRoleTree: false,
      roleName: ''
    }
  },
  created() {
    this.$nextTick(() => {
      this.crud.toQuery()
    })
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    ROLE() {
      return this.dict.ROLE.filter(item => {
        return item.value !== 'admin'
      })
    }
  },
  updated() {
    console.log(this.dict)
  },
  methods: {
    getTreeMap,
    [CRUD.HOOK.afterRefresh]() {
      this.$refs.menu.setCheckedKeys([])
    },
    // 编辑前
    // [CRUD.HOOK.beforeToEdit](crud, form) {
    //   if (form.dataScope === '自定义') {
    //     this.getDepts()
    //   }
    //   const depts = []
    //   crudRoles.getRoleDep(form.id).then(res => {
    //     res.forEach(function (dept, index) {
    //       console.info("dept=", dept)
    //       depts.push(dept.deptId)
    //     })
    //     form.depts = depts
    //   })
    // },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.dataScope === '自定义' && crud.form.depts.length === 0) {
        this.$message({
          message: '自定义数据权限不能为空',
          type: 'warning'
        })
        return false
      } else if (crud.form.dataScope === '自定义') {
        const depts = []
        crud.form.depts.forEach(function(data, index) {
          const dept = {
            id: data
          }
          depts.push(dept)
        })

        crud.form.depts = depts
      } else {
        crud.form.depts = []
      }
      return true
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      const depts = []
      crud.form.depts.forEach(function(dept, index) {
        depts.push(dept.id)
      })
      crud.form.depts = depts
    },
    // 获取所有菜单
    getMenus(val) {
      crudRoles.getAccessTree({
        roleId: val.id,
        type: 'menu'
      }).then(res => {
        this.menus = res
        const allNode = getTreeMap(res, 'children')
        const _allNode = allNode.filter(v => {
          return v.grant
        })
        this.menuIds = _allNode.map(v => {
          return v.id
        })
      })
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        this.roleName = val.name
        const _this = this
        // 清空菜单的选中
        // this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.id
        // 初始化
        this.menuIds = []
        // 菜单数据需要特殊处理
        this.getMenus(val)
        this.showRoleTree = true
      }
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true
      const role = {
        roleId: this.currentId,
        menus: []
      }
      // 得到半选的父节点数据，保存起来
      this.$refs.menu.getCheckedNodes(false, true).forEach(function(data, index) {
        role.menus.push(data.id)
      })
      crudRoles.editMenu(role).then(res => {
        this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.menuLoading = false
        // this.showRoleTree = false
        this.update()
      }).catch(err => {
        this.menuLoading = false
      })
    },
    // 改变数据
    update() {
      // 无刷新更新 表格数据
      crudRoles.get(this.currentId).then(res => {
        for (let i = 0; i < this.crud.data.length; i++) {
          if (res.id === this.crud.data[i].id) {
            this.crud.data[i] = res
            break
          }
        }
      })
    },
    // 获取部门数据
    getDepts() {
      getDepts({
        enabled: true
      }).then(res => {
        this.depts = res.content
      })
    },
    // 如果数据权限为自定义则获取部门数据
    changeScope() {
      if (this.form.dataScope === '自定义') {
        this.getDepts()
      }
    },
    checkboxT(row, rowIndex) {
      return row.level >= this.level
    }
  }
}

</script>

<style rel="stylesheet/scss" lang="scss">
  .role-span {
    font-weight: bold;
    color: #303133;
    font-size: 15px;
  }

</style>